package com.sky.controller;

import com.sky.entity.ChatRecord;
import com.sky.service.SparkAIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@Slf4j
public class AIController {

    @Autowired
    private SparkAIService sparkAIService;

    @PostMapping("/chat")
    public ResponseEntity<Map<String, String>> chatWithAI(
            @RequestParam String userId,
            @RequestParam String question) {

        try {
            String response = sparkAIService.chatWithAI(userId, question);
            Map<String, String> result = new HashMap<>();
            result.put("userId", userId);
            result.put("question", question);
            result.put("response", response);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("AI chat error for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    @PostMapping("/clear-history")
    public ResponseEntity<Map<String, String>> clearHistory(@RequestParam String userId) {
        sparkAIService.clearUserHistory(userId);
        return ResponseEntity.ok(Collections.singletonMap("message", "History cleared for user: " + userId));
    }

    /**
     * 查询用户与AI的历史对话记录
     * @param userId 用户ID
     * @param page 页码（从1开始），可选，默认值为1
     * @param pageSize 每页记录数，可选，默认值为10
     * @return 包含历史对话记录的响应实体
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getChatHistory(
            @RequestParam String userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        try {
            // 将字符串userId转换为Long类型
            Long userIdLong;
            try {
                userIdLong = Long.parseLong(userId);
            } catch (NumberFormatException e) {
                log.warn("用户ID格式不正确: {}", userId);
                return ResponseEntity.badRequest()
                        .body(Collections.singletonMap("error", "用户ID格式不正确"));
            }

            // 调用服务层获取历史记录
            List<ChatRecord> history = sparkAIService.getChatHistory(userIdLong, page, pageSize);

            // 构建响应
            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("history", history);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询用户{}历史对话记录失败", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "查询历史记录失败: " + e.getMessage()));
        }
    }
}